import io from 'socket.io-client'
export  default  {
  namespaced: true,
  state:{
    socket: null,
    user: {}
  },
  mutations:{
    setSocket(state, socket){
      state.socket = socket
    }
  },
  actions: {
    async connectSocket({commit, state, dispatch}, user) {
      state.user = user
      let socket = io.connect(`/?userId=${user?.userId}`, {reconnection: true});
      socket.on('connect', () => {
        console.log('连接成功');
        // 获取聊天室所需所有信息
        socket.emit('chatData', user);
        // 先保存好socket对象
        commit('setSocket', socket)
      })
      socket.on('joinFriendSocket', (res) => {
        console.log('on joinFriendSocket', res);
        if (!res.code) {
          console.log('成功加入私聊房间');
        }
      });

      socket.on('friendMessage', (res) => {
        console.log('on friendMessage', res);
        if (!res.code) {
        } else {
        }
      });
      socket.on('chatData', (res) => {
        // if (res.code) {
        //   return Vue.prototype.$message.error(res.msg);
        // }
        dispatch('handleChatData', res.data);
        // commit(SET_DROPPED, false);
      });

    },
    async handleChatData({commit, dispatch, state}, payload) {
      let user = state.user;
      let socket = state.socket;
      let friendArr = payload.friendData;
      if (friendArr.length) {
        for (let friend of friendArr) {
          socket.emit('joinFriendSocket', {
            userId: user.userId,
            friendId: friend.userId,
          });
        }
      }
    }
  }
}